package cn.sc.summer.mybatis.util;

import cn.hutool.core.collection.CollUtil;
import cn.sc.summer.redis.util.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 类名：负载均衡算法工具类
 *
 * @author a-xin
 * @date 2024/5/29 16:48
 */
@Slf4j
@Component
public class LoadBalancerUtil {

    /**
     * 根据轮询规则进行选取目标服务
     *
     * @param servers 需要选择的服务列表
     * @param key     redis存储key
     * @return 目标服务
     */
    public static String getNextServer(List<String> servers, @NonNull String key) {
        if (CollUtil.isEmpty(servers)) {
            throw new IllegalArgumentException("The load balancer list cannot be empty!");
        }
        if (RedisHelper.hasKey(key)) {
            RedisHelper.incr(key, 1);
            int i = Integer.parseInt(RedisHelper.get(key).toString());
            return servers.get((i + 1) % servers.size());
        } else {
            RedisHelper.set(key, 1);
            return servers.get(0);
        }
    }

}
